@<template>
  <div>
    <!-- 面包屑导航区 -->
    <breadcrumb :breadInfo="breadInfo" />

    <!-- 卡片视图区 -->
    <el-card>
      <!-- 提示警告区域 -->
      <el-alert
        show-icon
        :closable="false"
        title="注意: 只允许为第三级分类设置相关参数"
        type="warning"
      >
      </el-alert>

      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col :span="14">
          <span>请选择商品分类:</span>
          <el-cascader
            v-model="selectCateKeys"
            :options="cateList"
            :props="cascaderProps"
            @change="cascaderChange"
          ></el-cascader>
        </el-col>
      </el-row>
      
      <!-- tabs标签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="move_params">
          <el-button
            size="mini"
            :disabled="hasData"
            type="primary"
            @click="toAddParmas"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table
            v-if="addMoveParams.length != 0"
            :data="addMoveParams"
            border
            style="width: 100%"
          >
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  @close="handleClose(item, scope.row)"
                  class="el-tag"
                  v-for="item in scope.row.attr_vals"
                  :key="item"
                  >{{ item }}</el-tag
                >
                
                <!-- 新增tag按钮 -->
                <el-input
                  class="input-new-tag"
                  v-if="inputVisible"
                  v-model="inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                  
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  class="el-icon-edit"
                  @click="editParams(scope.row)"
                  >修改</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  class="el-icon-delete"
                  @click="deleteParams(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="static_params">
          <el-button
            size="mini"
            type="primary"
            @click="toAddParmas"
            :disabled="hasData"
            >添加属性</el-button
          >
          <!-- 静态属性表格-->
          <el-table
            v-if="addMoveParams.length != 0"
            :data="addMoveParams"
            border
            style="width: 100%"
          >
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  @close="handleClose(item, scope.row)"
                  closable
                  v-for="item in scope.row.attr_vals"
                  :key="item"
                  >{{ item }}</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  class="el-icon-edit"
                  @click="editParams(scope.row)"
                  >修改</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  class="el-icon-delete"
                  @click="deleteParams(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加动态参数对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="addParamsDialogVisible"
      width="50%"
      @close="addParamsDialogClosed"
    >
      <!-- 添加内容区域 -->
      <el-form
        :model="addParamsForm"
        :rules="addParamsFormRules"
        ref="addParamsFormRef"
        label-width="80px"
      >
        <el-form-item :label="dialogLabel" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAddParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑参数对话框 -->
    <el-dialog
      :title="'编辑' + dialogLabel"
      :visible.sync="editParamsDialogVisible"
      width="50%"
      @close="editParamsDialogClosed"
    >
      <!-- 添加内容区域 -->
      <el-form
        :model="editParamsForm"
        :rules="addParamsFormRules"
        ref="editParamsFormRef"
        label-width="80px"
      >
        <el-form-item :label="dialogLabel" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmEditParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Breadcrumb from "../../common/breadcrumb/Breadcrumb.vue";

export default {
  components: { Breadcrumb },
  data() {
    return {
      breadInfo: ["商品管理", "分类参数"],
      // 存储商品分类
      cateList: [],
      // 级联选择器 绑定的列表
      selectCateKeys: [],
      // 级联选择器配置对象
      cascaderProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      activeName: "move_params",
      // 参数对象
      addMoveParams: [],
      type: "many",
      // 添加参数的对象
      addParamsForm: {
        attr_name: "",
        attr_sel: "many",
        attr_vals: "",
      },
      // 控制添加参数对话框的显示或隐藏
      addParamsDialogVisible: false,
      // 预验证规则
      addParamsFormRules: {
        attr_name: [
          { required: true, message: "请输入相应内容", trigger: "blur" },
        ],
      },
      // 控制添加参数按钮
      hasData: true,
      // 对话框抬头
      dialogTitle: "添加动态参数",
      dialogLabel: "动态参数",
      editParamsDialogVisible: false,
      // 编辑参数 绑定对象
      editParamsForm: {},
      // 
      inputVisible: false,
      // 
      inputValue: ""
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    // 获取所有商品分类的数据
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200)
        return this.$message.error("获取商品分类失败");

      // 获取成功
      this.cateList = res.data;
    },
    // 级联选择器发生变化的事件处理函数
    cascaderChange() {
      // 仅支持选择第三级分类
      if (this.selectCateKeys.length < 3) {
        this.selectCateKeys = [];
        // 没有数据, 添加参数按钮不可点击
        this.hasData = true;
        // 数据清空
        this.addMoveParams = [];
        return;
      }

      this.getParams();
    },
    // 点击标签的事件处理函数
    handleClick() {
      if (this.activeName == "move_params") {
        this.addParamsForm.attr_sel = "many";
        this.dialogTitle = "添加动态参数";
        this.dialogLabel = "动态参数";
      } else {
        this.addParamsForm.attr_sel = "only";
        this.dialogTitle = "添加静态属性";
        this.dialogLabel = "静态属性";
      }
      this.getParams();
    },
    // 获取动态或静态参数的方法
    async getParams() {
      if (this.selectCateKeys.length == 0) return (this.hasData = true);

      //  获取商品id值
      let goodsId = this.lastIndex;
      // 获取参数列表
      const { data: res } = await this.$http.get(
        `categories/${goodsId}/attributes`,
        { params: { sel: this.addParamsForm.attr_sel } }
      );
      if (res.meta.status !== 200) return this.$message.error("获取参数失败");
      this.addMoveParams = res.data;
      this.addMoveParams.forEach((item) => {

        item.attr_vals = item.attr_vals.split(",").includes("")
          ? []
          : item.attr_vals.split(",");
        // 控制添加tag的展示与隐藏
       
        item.inputVisible = false
        item.inputValue = ''

      });

      // 添加参数按钮 可点击
      this.hasData = false;
    },
    // 对话框关闭函数
    addParamsDialogClosed() {
      // 重置表单
      this.$refs.addParamsFormRef.resetFields();
    },
    // 添加参数按钮
    toAddParmas() {
      this.addParamsDialogVisible = true;
    },

    // 确定添加参数或属性
    confirmAddParams() {
      // 预验证表单
      this.$refs.addParamsFormRef.validate(async (valid) => {
        if (!valid) return;

        // 验证通过, 开始发送网络请求
        const { data: res } = await this.$http.post(
          `categories/${this.lastIndex}/attributes`,
          this.addParamsForm
        );

        if (res.meta.status !== 201)
          return this.$message.error(`${this.dialogLabel}添加失败`);
        this.$message.success(`${this.dialogLabel}添加成功`);
        // 更新数据
        this.getParams();
        // 关闭对话框
        this.addParamsDialogVisible = false;
      });
    },
    // 删除按钮
    deleteParams(rowInfo) {
      // 弹窗确认
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // 发出删除请求
          const { data: res } = await this.$http.delete(
            `categories/${this.lastIndex}/attributes/${rowInfo.attr_id}`
          );
          if (res.meta.status !== 200)
            return this.$message.error(`${this.dialogLabel}删除失败`);
          // 更新数据
          this.getParams();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 编辑按钮
    async editParams(rowInfo) {
      this.editParamsForm = rowInfo;
      // 弹出对话框
      this.editParamsDialogVisible = true;
    },
    // 编辑对话框关闭事件函数
    editParamsDialogClosed() {},
    // 编辑对话框确认按钮
    confirmEditParams() {
      //数据预验证
      this.$refs.editParamsFormRef.validate(async (valid) => {
        if (!valid) return;

        // 深拷贝
        let newParamsForm = JSON.parse(JSON.stringify(this.editParamsForm));

        // 后台attr_vals属性接收字符串,
        newParamsForm.attr_vals = newParamsForm.attr_vals.join(",");

        // 验证通过, 发出修改请求
        const { data: res } = await this.$http.put(
          `categories/${this.lastIndex}/attributes/${this.editParamsForm.attr_id}`,
          newParamsForm
        );
        if (res.meta.status !== 200)
          return this.$message.error(`${this.dialogLabel}更新失败`);

        this.$message.success(`${this.dialogLabel}更新成功`);
        // 更新数据
        this.getParams();
        // 关闭对话框
        this.editParamsDialogVisible = false;
      });
    },
    // tag标签关闭事件
    handleClose(item, rowInfo) {
      // 从数组中删除
      let itemIndex = rowInfo.attr_vals.indexOf(item);
      rowInfo.attr_vals.splice(itemIndex, 1);
      this.saveAttr(rowInfo)
    },
    // 新增tag 回车或enter后的事件处理函数
    handleInputConfirm(rowInfo) {
      this.inputVisible = false
      console.log("失去焦点")
      if (this.inputValue.length == 0) return
      // 前端页面,添加数据
      rowInfo.attr_vals.push(this.inputValue)
      // 后端写入数据
      this.saveAttr(rowInfo)

      this.inputValue = ""
      
      
    },
    // 点击tag按钮事件
    showInput(rowInfo) {
      this.inputVisible = true
      
      
    },
    // 保存参数
    async saveAttr(rowInfo) {
      // 深拷贝
      let newRowInfo = JSON.parse(JSON.stringify(rowInfo));

      // 后台attr_vals属性接收字符串,
      newRowInfo.attr_vals = newRowInfo.attr_vals.join(",")
      // 提交参数
      const { data: res } = await this.$http.put(
        `categories/${this.lastIndex}/attributes/${rowInfo.attr_id}`,
        { attr_name: newRowInfo.attr_name, attr_sel: newRowInfo.attr_sel, attr_vals: newRowInfo.attr_vals }
      );
    }
  },
  computed: {
    lastIndex() {
      return this.selectCateKeys[this.selectCateKeys.length - 1];
    },
  },
};
</script>

<style lang="less" scoped>
.cat_opt {
  margin-top: 10px;
  font-size: 18px;
}
.el-cascader {
  margin-left: 10px;
  width: 220px;
}

.el-tag {
  margin: 5px 10px;
}
.input-new-tag {
  width: 140px;
}
</style>